const HttpException = require("../exceptions/http_expetion");
const User = require("../models/user");

//添加关注
module.exports.follow = async (req, res, next) => {
  try {
    //获取信息
    const username = req.params.username;
    //校验用户是否存在
    const userA = await User.findOne({ where: { username } });
    if (!userA) {
      throw new HttpException(404, "被关注用户不存在！！！", "user is not!!! ");
    }
    //关注者信息
    const { email } = req.user;
    //获取用户信息
    const userB = await User.findByPk(email);
    //添加关注；建立关系
    await userA.addFollowers(userB);
    //返回被关注者信息
    const profile = {
      username: userA.username,
      bio: userA.bio,
      avatar: userA.avatar,
      following: true,
    };
    res.status(200).json({
      status: 1,
      message: "关注成功！！！",
      data: profile,
    });
  } catch (err) {
    next(err);
  }
};

//取消关注
module.exports.cancelFollow = async (req, res, next) => {
  try {
    //获取信息
    const username = req.params.username;
    //校验用户是否存在
    const userA = await User.findOne({ where: { username } });
    if (!userA) {
      throw new HttpException(404, "被关注用户不存在！！！", "user is not!!! ");
    }
    //关注者信息
    const { email } = req.user;
    //获取用户信息
    const userB = await User.findByPk(email);
    //取消关注
    await userA.removeFollowers(userB);
    //返回被关注者信息
    const profile = {
      username: userA.username,
      bio: userA.bio,
      avatar: userA.avatar,
      following: false,
    };
    res.status(200).json({
      status: 1,
      message: "取消关注成功！！！",
      data: profile,
    });
  } catch (err) {
    next(err);
  }
};

//获取粉丝
module.exports.getFollowers = async (req, res, next) => {
  try {
    //获取作者信息
    const username = req.params.username;
    //验证作者是否存在
    const userA = await User.findOne({ 
      where: { username } ,
      include:['followers']
    });
    if (!userA) {
      throw new HttpException(404, "被关注用户不存在！！！", "user is not!!! ");
    }
    //验证当前登录是否关注作者
    const {email} = req.user
    let following = false
    let followers =[]
    for (const user of userA.followers) {
      if (email===user.dataValues.email) {
        following = true
      }
      delete user.dataValues.password //删除粉丝信息的密码
      delete user.dataValues.Followers 
      followers.push(user.dataValues)
    }
    //返回粉丝信息
    const profile = {
      username:userA.username,
      bio:userA.bio,
      avatar:userA.avatar,
      following,
      followers,
    }
    res.status(200)
        .json({
          status:1,
          message:'获取粉丝信息成功！！！',
          data:profile
        })
  } catch (err) {
    next(err);
  }
};
